import axios from 'axios'
import { getToken } from '@/utils/auth'
import { API_HOST } from '@/env'
import HttpStatusCode from './status_code'

import router from '../router'

const service = axios.create({
  baseURL: API_HOST,
  timeout: 60000 * 5
})

service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  (err) => {
    console.log(err)
  }
)
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    const errStr = error.toString()

    if (errStr && errStr.includes('Network Error')) {
      window.notyf.error('无法连接到服务器')
    }
    if (error.response) {
      switch (error.response.status) {
        case HttpStatusCode.HTTP_400_BAD_REQUEST:
        case HttpStatusCode.HTTP_422_UNPROCESSABLE_ENTITY:
          const errmsg = error.response && error.response.data && error.response.data.errmsg
          window.notyf.error(errmsg || '参数错误')
          break
        case HttpStatusCode.HTTP_401_UNAUTHORIZED:
          window.notyf.error('请先登录')
          await router.push('/login')
          return
        default:
          window.notyf.error('请求失败')
          break
      }
    }

    return Promise.reject(error)
  }
)

export default service
